<template>
  <view>
    <uni-search-bar placeholder="请输入内容" @confirm="confirm" @input="input"></uni-search-bar>
    <view class="search-list" v-if="!isSearch">
      <view class="search-title">
        <text>搜索记录</text>
        <uni-icons type="trash" size="20" @click="clearSearchList"></uni-icons>
      </view>
      <uni-tag class="search-list-item" v-for="(v, i) in searchList" :key="i" :text="v" type="primary" />
    </view>
    <view class="advice-list" v-else>
      <view class="advice-title" @click="goToDetail(v)" v-for="(v, i) in adviceList" :key="i">{{ v.goods_name }}</view>
    </view>
  </view>
</template>

<script>
  export default {
    methods: {
      goToDetail(v){
        uni.navigateTo({
          url: '/subpkg/detail/detail?goods_id=' + v.goods_id
        })
      },
      confirm(e) {
        // 获取搜索的值
        const value = e.value;
        // 将搜索的值保存本地存储
        this.searchList.unshift(value)
        // 去除重复
        this.searchList = [...new Set(this.searchList)]
        // 跳转搜索结果页面
        uni.navigateTo({
          url: `/subpkg/detail_list/detail_list?name=${value}&query=${value}`
        })
      },
      clearSearchList() {
        this.searchList = []
      },
      input(value) {
        this.isSearch = value.length > 0
        // 节流操作
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.preSearch(value)
        }, 400)
      },
      async preSearch(value) {
        const [error, resp] = await uni.request({
          url: `https://www.uinav.com/api/public/v1/goods/qsearch?query=${value}`
        })
        this.adviceList = resp.data.message
      }
    },
    watch: {
      searchList(newValue) {
        uni.setStorageSync('searchList', this.searchList)
      }
    },
    data() {
      return {
        adviceList: [],
        searchList: uni.getStorageSync('searchList') || [],
        timer: null,
        isSearch: false
      };
    }
  }
</script>

<style lang="scss">
  .advice-list {
    .advice-title {
      border-bottom: 1upx solid #ccc;
      line-height: 36px;
      height: 36px;
      width: 100vw;
      box-sizing: border-box;
      padding: 0upx 20upx;
      margin: 10upx 0;
      // 省略号
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;

    }
  }

  .search-list {
    padding: 20upx;

    .search-title {
      display: flex;
      justify-content: space-between;

      >text {
        font-weight: bold;
      }
    }

    .search-list-item {
      margin-right: 16upx;
    }
  }
</style>
